package com.lifuixng.picturebackend.manage.upload;

import cn.hutool.core.io.FileUtil;
import com.lifuixng.picturebackend.exception.ErrorCode;
import com.lifuixng.picturebackend.exception.ThrowUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @Author Mr.LiFuXing
 * @Date 2024/12/22 20:49
 * @Title FilePictureUpload
 * @Package com.lifuixng.picturebackend.manage.upload
 */
@Service
public class FilePictureUpload extends PictureUploadTemplate {
    @Override
    protected void verifyPicture(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "文件不能为空");
        // 1. 校验图片 大小 图片类型
        long filesize = multipartFile.getSize();
        // 1M
        final long ONE_M = 1024 * 1024L;
        ThrowUtils.throwIf(filesize > ONE_M * 2, ErrorCode.OPERATION_ERROR, "上传图片大小不能超过2M");
        // 获取文件的后缀名 jpg png
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final List<String> ALLOW_SUFFIX = Arrays.asList("jpg", "png", "webp", "jpeg");
        ThrowUtils.throwIf(!ALLOW_SUFFIX.contains(fileSuffix), ErrorCode.SYSTEM_ERROR, "文件类型错误");
    }

    @Override
    protected String getOriginalFilename(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        return multipartFile.getOriginalFilename();
    }

    @Override
    protected void processFile(Object inputSource, File file) throws IOException {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        multipartFile.transferTo(file);
    }
}
